package com.mingtu.jgspatrol.activity;

import static com.mingtu.common.utils.MyUtills.getBounds;
import static com.mingtu.jgspatrol.utils.MyConstant.MAP_INDEX;
import static com.mingtu.jgspatrol.utils.MyConstant.MAX_ZOOM;

import android.os.Bundle;
import android.util.Pair;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.maps.model.TileOverlay;
import com.amap.api.maps.model.TileOverlayOptions;
import com.amap.api.maps.utils.SpatialRelationUtil;
import com.amap.api.maps.utils.overlay.MovingPointOverlay;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.center.bean.TrackDetailsPointBean;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.GZip.GZipUtil;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.PathSmoothTool;
import com.mingtu.common.utils.StatusBarUtil;
import com.mingtu.common.utils.TileUtils;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.base.MyBaseActivity;
import com.mingtu.jgspatrol.databinding.ActivityTrackDetailsNewBinding;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class TrackDetailsActivity extends MyBaseActivity<ActivityTrackDetailsNewBinding> {
    private AMap aMap;
    private List<Marker> markers = new CopyOnWriteArrayList<>();
    private List<Polyline> polylines = new CopyOnWriteArrayList<>();
    private List<Polyline> movePolylines = new CopyOnWriteArrayList<>();
    private String trackId;
    private List<LatLng> pausePoints = new ArrayList<>(); //存储暂停的点
    private List<LatLng> moveTrackList = new ArrayList<>();
    private MovingPointOverlay smoothMarker;
    private List<LatLng> myPointList;
    private Marker moveMarker;
    private int moveTime = 6;
    //自定义瓦片图层
    private TileOverlayOptions tileOverlayOptions = null;
    private TileOverlay tileOverlay;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_track_details_new;
    }

    @Override
    protected void initView() {
        setModuleTitle("轨迹详情");
        hideHeadView();
        StatusBarUtil.addStatusBarHeight(binding.statusBarView);
        ImmersionBar immersionBar = ImmersionBar.with(this);
        immersionBar.statusBarDarkFont(false);
        immersionBar.init();
    }

    @Override
    protected void initData() {
        addClickListener(this, binding.ivBack);
    }

    @Override
    protected void getData() {
        //轨迹
        trackId = getIntent().getStringExtra("trackId");
        if (!StringUtils.isEmpty(trackId)) {
            getTrack();
        } else {
            ToastUtils.showLong("数据获取错误！");
        }

    }

    @Override
    protected void initMap(Bundle savedInstanceState) {
        super.initMap(savedInstanceState);
        binding.mapView.onCreate(savedInstanceState);
        aMap = binding.mapView.getMap();
        //地图模式可选类型：MAP_TYPE_NORMAL,MAP_TYPE_SATELLITE,MAP_TYPE_NIGHT
        aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 矢量地图模式
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.setMaxZoomLevel(MAX_ZOOM);
        aMap.setMapTextZIndex(1);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(Constant.MAP_ZOOM));

        //自定义瓦片图层
        tileOverlayOptions = TileUtils.getTileOverlayOptions();
        tileOverlay = aMap.addTileOverlay(tileOverlayOptions);
    }

    @Override
    protected void onResume() {
        super.onResume();
        binding.mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        binding.mapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，
        //保存地图当前的状态
        binding.mapView.onSaveInstanceState(outState);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (markers.size() > 0) {
            for (Marker marker : markers) {
                marker.remove();
            }
        }

        if (polylines.size() > 0) {
            for (Polyline polyline : polylines) {
                polyline.remove();
            }
        }

        if (movePolylines.size() > 0) {
            for (Polyline polyline : movePolylines) {
                polyline.remove();
            }
        }
        if (smoothMarker != null) {
            smoothMarker.stopMove();
        }

        if (smoothMarker != null) {
            smoothMarker.stopMove();
            smoothMarker.setMoveListener(null);
            smoothMarker.destroy();
        }

        //自定义瓦片
        if (tileOverlay != null) {
            tileOverlayOptions.visible(false);
            tileOverlay.remove();
        }

        markers.clear();
        polylines.clear();
        movePolylines.clear();

        //销毁地图对象
        if (aMap != null) {
            binding.mapView.onDestroy();
        }

    }


    /**
     * 根据trackId 查询轨迹点
     */
    private void getTrack() {
        PathSmoothTool mpathSmoothTool = new PathSmoothTool();
        mpathSmoothTool.setIntensity(Constant.Intensity);
        mpathSmoothTool.setThreshhold(0);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", trackId);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(Constant.getInstance().POST_SEARCH_TRACK + "/" + trackId)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            JSONObject jsonObject = JSON.parseObject(result);
                            String msg = jsonObject.getString("msg");
                            if (msg.equals(Constant.RESULT_SUCCESS)) {
                                String points = jsonObject.getString("points"); //经过压缩的轨迹点
                                String myPoints = GZipUtil.uncompress(points);
                                JSONArray jsonArray = JSON.parseArray(myPoints);
                                HashMap<String, Object> hashMap = new HashMap<>();
                                hashMap.put("points", jsonArray);
                                String myData = GsonUtils.toJson(hashMap);

                                try {
                                    Gson gson = GsonFactory.getSingletonGson();
                                    TrackDetailsPointBean trackDetailsPointBean = new TrackDetailsPointBean();
                                    trackDetailsPointBean = gson.fromJson(myData, TrackDetailsPointBean.class);

                                    List<TrackDetailsPointBean.PointsBean> pointsBeans = trackDetailsPointBean.getPoints();

                                    List<List<LatLng>> trackList = new ArrayList<>();
                                    myPointList = new ArrayList<>();
                                    List<LatLng> latLngs = null;
                                    for (int i = 0; i < pointsBeans.size(); i++) {
                                        TrackDetailsPointBean.PointsBean pointsBean = pointsBeans.get(i);
                                        String lat = pointsBean.getLat();
                                        String lng = pointsBean.getLng();
                                        boolean pointFlag = pointsBean.isPointflag();

                                        double myLat = Double.parseDouble(lat);
                                        double myLng = Double.parseDouble(lng);
                                        LatLng latLng = new LatLng(myLat, myLng);
                                        myPointList.add(latLng); //为了能看到中断的全部轨迹
                                        if (i == 0) {
                                            latLngs = new ArrayList<LatLng>();
                                            latLngs.add(latLng);
                                        } else {
                                            if (pointFlag) {  //轨迹中间出现暂停
                                                trackList.add(latLngs);
                                                latLngs = new ArrayList<LatLng>();
                                                latLngs.add(latLng);
                                                if (i == pointsBeans.size() - 1) {
                                                    trackList.add(latLngs);
                                                }
                                                pausePoints.add(latLng);//存放暂停点
                                            } else {
                                                latLngs.add(latLng);
                                                if (i == pointsBeans.size() - 1) {
                                                    trackList.add(latLngs);
                                                }
                                            }
                                        }
                                    }

                                    //去重
                                    myPointList = new ArrayList<LatLng>(new LinkedHashSet<LatLng>(myPointList));
                                    float distance = MyUtills.getDistance(myPointList); //计算距离，根据距离动态设置轨迹移动的时间
                                    moveTime = MyUtills.getMoveTime(distance);

////                                    myPointList = mpathSmoothTool.pathOptimize(myPointList); //此处做圆滑处理后，分段的轨迹，在移动的时候会出现和原始估计不一样的问题
//                                    for (int i = 0; i < trackList.size(); i++) {
//                                        List<LatLng> trackItem = trackList.get(i);
//                                        List<LatLng> trackItemOp = mpathSmoothTool.pathOptimize(trackItem);
//                                        //绘制线路
//                                        Polyline mapPolyline = aMap.addPolyline(new PolylineOptions()
//                                                .addAll(trackItemOp)
//                                                .width(Constant.POLYLINE_WIDTH)
//                                                .color(getResources().getColor(R.color.colorPrimary)));
//                                        polylines.add(mapPolyline);
//
//
//                                        if (i == 0) {
//                                            //添加开始Marker
//                                            MarkerOptions startMarkerOptions = new MarkerOptions()
//                                                    .position(trackItemOp.get(0))
//                                                    .icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_start));
//                                            Marker startMarker = aMap.addMarker(startMarkerOptions);
//                                            markers.add(startMarker);
//
//                                        }
//
//                                        if (i == trackList.size() - 1) {
//                                            //添加结束Marker
//                                            MarkerOptions endMarkerOptions = new MarkerOptions()
//                                                    .position(trackItemOp.get(trackItemOp.size() - 1))
//                                                    .icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_end));
//                                            Marker endMarker = aMap.addMarker(endMarkerOptions);
//                                            markers.add(endMarker);
//
//                                        }
//                                    }
                                    aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(getBounds(myPointList), 200));


                                    // 取轨迹点的第一个点 作为 平滑移动的启动
                                    LatLng drivePoint = myPointList.get(0);
                                    Pair<Integer, LatLng> pair = SpatialRelationUtil.calShortestDistancePoint(myPointList, drivePoint);
                                    myPointList.set(pair.first, drivePoint);
                                    List<LatLng> subList = myPointList.subList(pair.first, myPointList.size());

                                    if (smoothMarker == null) {
                                        // 设置 平滑移动的 图标
                                        ArrayList<BitmapDescriptor> giflist = new ArrayList<BitmapDescriptor>();
                                        giflist.add(BitmapDescriptorFactory.fromResource(R.mipmap.icon_people01));
//                                        giflist.add(BitmapDescriptorFactory.fromResource(R.mipmap.icon_people02));
                                        giflist.add(BitmapDescriptorFactory.fromResource(R.mipmap.icon_people03));
//                                        giflist.add(BitmapDescriptorFactory.fromResource(R.mipmap.icon_people04));

                                        moveMarker = aMap.addMarker(new MarkerOptions()
                                                .zIndex(MAP_INDEX)
                                                .anchor(0.5f, 0.5f)
                                                .icons(giflist));

                                        smoothMarker = new MovingPointOverlay(aMap, moveMarker);
                                    }

                                    smoothMarker.setPoints(subList); // 设置轨迹点
                                    smoothMarker.setTotalDuration(moveTime);// 设置平滑移动的总时间  单位  秒
                                    smoothMarker.setMoveListener(new MovingPointOverlay.MoveListener() {
                                        int num = 0;
                                        int[] doublePointIndex = {0, 1};

                                        @Override
                                        public void move(final double distance) {
                                            num += 1;
                                            int index = smoothMarker.getIndex();
                                            if (num == 1) {
                                                doublePointIndex[0] = 0;
                                                return;
                                            } else {
                                                doublePointIndex[1] = index;
                                            }
                                            List<LatLng> sub = myPointList.subList(doublePointIndex[0], doublePointIndex[1]);
                                            for (LatLng latLng : sub) {
                                                moveTrackList.add(latLng);
                                                if (pausePoints.contains(latLng)) {
                                                    moveTrackList.clear();
                                                    moveTrackList.add(latLng);
                                                } else {
                                                    if (moveTrackList.size() >= 2) { //两段成一条线，画线完成后把之前的坐标数组清除，并把当前坐标添加进去
                                                        Polyline mapPolyline = aMap.addPolyline(new PolylineOptions()
                                                                .addAll(moveTrackList)
                                                                .width(Constant.POLYLINE_WIDTH)
                                                                .zIndex(MAP_INDEX)
                                                                .color(getResources().getColor(R.color.colorPrimary)));
                                                        movePolylines.add(mapPolyline);
                                                        moveTrackList.clear();
                                                        moveTrackList.add(latLng); //清除之前的数组之后，添加当前的坐标

                                                    }

                                                }

                                                aMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); //此处animateCamera   moveCamera两个地方同时使用一个的话，效果不好
                                                aMap.moveCamera(CameraUpdateFactory.changeTilt(35));

                                            }
                                            doublePointIndex[0] = index; //将上段的终点坐标作为起点
                                            moveTrackList.clear();
                                            if (sub.size() > 0) { //将分割后的段落的最后一个坐标添加到下个分割段落
                                                moveTrackList.add(sub.get(sub.size() - 1));
                                            } else {
                                                moveTrackList.add(sub.get(0));
                                            }

                                            if (distance == 0) {
                                                if (index < myPointList.size() - 1) {
                                                    if (myPointList.size() > 0) {
                                                        List<LatLng> endList = myPointList.subList(index, myPointList.size());
                                                        moveTrackList.addAll(endList);
                                                        Polyline mapPolyline = aMap.addPolyline(new PolylineOptions()
                                                                .addAll(moveTrackList)
                                                                .width(Constant.POLYLINE_WIDTH)
                                                                .zIndex(MAP_INDEX)
                                                                .color(getResources().getColor(R.color.colorPrimary)));
                                                        movePolylines.add(mapPolyline);
                                                    }
                                                }

                                                smoothMarker.stopMove();
                                                //添加结束Marker
                                                MarkerOptions endMarkerOptions = new MarkerOptions()
                                                        .position(myPointList.get(myPointList.size() - 1))
                                                        .zIndex(MAP_INDEX)
                                                        .icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_end));
                                                Marker endMarker = aMap.addMarker(endMarkerOptions);
                                                markers.add(endMarker);

                                                moveMarker.remove();

                                                aMap.animateCamera(CameraUpdateFactory.changeTilt(0));
                                                aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(getBounds(myPointList), 200));
                                            }
                                        }
                                    });
                                    // 开始移动
                                    smoothMarker.startSmoothMove();
                                    //添加开始Marker
                                    MarkerOptions startMarkerOptions = new MarkerOptions()
                                            .position(myPointList.get(0))
                                            .zIndex(MAP_INDEX)
                                            .icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_start));
                                    Marker startMarker = aMap.addMarker(startMarkerOptions);
                                    markers.add(startMarker);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }


                            }

                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);

                    }
                });

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_back:
                ActivityUtil.removeActivity(this);
                break;
        }
    }
}

